#!/bin/sh

# wrapper script to set up environment for butch-core
# and redirects to several extension scripts
# + aliases to some commands

[ "$STAGE" = "0" ] && [ -z "$CONFIG" ] && CONFIG="$PWD/config"
[ -z "$CONFIG" ] && CONFIG=/src/config

if [ ! -e "$CONFIG" ] ; then
	echo "error: $CONFIG not found"
	exit 1
fi

. "$CONFIG"

BINDIR=$(dirname "$(readlink -f "$0")")

usage() {
cat << EOF >&2
butch wrapper v0.1.1

usage: $0 command package ...

------- available commands -----
list:		list all installed packages
files:		show all files installed by package
owner:		shows which package owns a file
search:		search for term in package names (grep syntax)
unlink:		removes symlinks from /opt/packagename into /
relocate:	creates symlinks for all files under /opt/packagename to /
relink:		==relocate
update:		update all packages whose hash changed
install:	download, build, relocate package(s) and all missing dependencies
build:		==install
prefetch:	download package(s) and all missing dependencies
print:		pretty-print the specified package
download:	==prefetch
rebuild:	unlink, download, rebuild, relocate package(s), but not their dependencies
checktarballs:	check if filesize of tarballs (if existent) matches packages

all download related actions are only done when needed, i.e. the tarball is missing.

examples:
butch build nano strace gdb
butch files busybox
butch owner /bin/gcc

butch unlink gettext #temporarily unlinks gettext
( do some work... for example check if package XY builds without gettext)
butch relink gettext #put it back into place

EOF
}

prog=butch-core
case $1 in
	build) shift ; set -- install "$@";;
	download) shift ; set -- prefetch "$@";;
	list) shift; prog=butch-list;;
	owner) shift; prog=butch-owner;;
	files) shift; prog=butch-files;;
	search) shift; prog=butch-search;;
	print) shift; prog=butch-print;;
	checktarballs) shift; prog=butch-checktarballs;;
	unlink) shift ; prog=butch-unlink;; #remove links of pkg
	relink|relocate) shift; prog=butch-relocate;; #relinks the pkg into /
	update) export BUTCH_SKIPLIST=gcc3:stage0:stage0_musl:stage0_gcc:stage0_prepare:"$BUTCH_SKIPLIST" ;;
	install|prefetch|rebuild) : ;;
	*) usage;; # we exec anyway to get butch-core's usage info
esac

exec "$BINDIR"/$prog "$@"

